package com.wwwzh.himalayafm.fragment.disfragment;


import android.annotation.TargetApi;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.animation.LinearInterpolator;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.Toast;

import com.wwwzh.himalayafm.R;
import com.wwwzh.himalayafm.adapter.ranking.DisRankItemAdapter;
import com.wwwzh.himalayafm.entity.ranking.DisRankEntity;
import com.wwwzh.himalayafm.fragment.disfragment.ranking.DisRankHttpService;
import com.wwwzh.himalayafm.fragment.subfragment.MyItemDecorations;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * A simple {@link Fragment} subclass.
 * 榜单界面
 */
public class RankingFragment extends Fragment implements Callback<DisRankEntity>, View.OnClickListener {
    private RecyclerView recylerView;
    private RelativeLayout relativeLayout;
    private Animation animation;
    private LinearLayout linearLayout;
    private RelativeLayout noNect;
    private Button button;
    private DisRankItemAdapter itemAdapter;
    private Context context;

    public RankingFragment() {
        // Required empty public constructor
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        context = getContext();
    }

    @TargetApi(Build.VERSION_CODES.M)
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment


        //初始化视图
        View rootView = inflater.inflate(R.layout.fragment_ranking, container, false);
        linearLayout = (LinearLayout) rootView.findViewById(R.id.DisRankFrag_LL);
        noNect = (RelativeLayout) rootView.findViewById(R.id.DisRankNoNet_RL);
        button = (Button) rootView.findViewById(R.id.DisRankNoNet_Btn);
//        nestedScrollView = (NestedScrollView) rootView.findViewById(R.id.DisRank_NS);
        recylerView = (RecyclerView) rootView.findViewById(R.id.DisRankItem_RL);


        return rootView;
    }


    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        Log.d("wen", "onViewCreated");
        button.setOnClickListener(this);
//        nestedScrollView.post(new Runnable() {
//            @Override
//            public void run() {
//                nestedScrollView.scrollTo(0, 0);
//            }
//        });
//        nestedScrollView.setVisibility(View.GONE);
        //imageView = (ImageView) rootView.findViewById(R.id.DisRank_IV);
        recylerView.setVisibility(View.GONE);
        MyItemDecorations itemDecorations = new MyItemDecorations(5);
        recylerView.addItemDecoration(itemDecorations);
        if (checkNet()) {


//            recylerView.setVisibility(View.VISIBLE);
            noNect.setVisibility(View.GONE);

            downLoadData();

        } else {

//            recylerView.setVisibility(View.GONE);
            noNect.setVisibility(View.VISIBLE);


        }

    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        recylerView = null;
        System.gc();
    }

    public RecyclerView getRecylerView() {
        return recylerView;
    }

    //
    @Override
    public void onResponse(Call<DisRankEntity> call, Response<DisRankEntity> response) {

        if (response.body() != null) {

            updateData(response.body());
        }
    }

    @Override
    public void onFailure(Call<DisRankEntity> call, Throwable t) {
        Context context = getContext();
        if (context != null) {

            Toast.makeText(context, "数据下载失败", Toast.LENGTH_SHORT).show();
        }
        removeLoadAnim();
        noNect.setVisibility(View.VISIBLE);
    }


    //检查是否有网络连接，以及网络连接是否可用
    private boolean checkNet() {
        ConnectivityManager connectivityManager = (ConnectivityManager) getContext().getSystemService(Context.CONNECTIVITY_SERVICE);
        boolean net = false;
        if (connectivityManager != null) {
            NetworkInfo info = connectivityManager.getActiveNetworkInfo();
            if (info != null && info.isConnected()) {
                if (info.getState() == NetworkInfo.State.CONNECTED) {
                    net = true;
                } else {
                    net = false;
                }
            } else {
                net = false;
            }
        }
        return net;
    }

    private void downLoadData() {
        addLoadAnim();
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl("http://mobile.ximalaya.com/")
                .addConverterFactory(GsonConverterFactory.create())
                .build();
        DisRankHttpService service = retrofit.create(DisRankHttpService.class);
        service.getDiaRankData().enqueue(this);

    }

    //更新数据
    private void updateData(DisRankEntity entity) {

        if (recylerView != null){

            itemAdapter = new DisRankItemAdapter(context, entity);
            recylerView.setAdapter(itemAdapter);
            //移除 "加载中" 动画
            removeLoadAnim();
            //使 有数据的视图可见
            recylerView.setVisibility(View.VISIBLE);
        }
        //nestedScrollView.setVisibility(View.VISIBLE);
        //nestedScrollView.scrollTo(0, 0);
    }


    //添加 "加载中" 动画
    private void addLoadAnim() {

        View viewLoad = LayoutInflater.from(getContext()).inflate(R.layout.layout_loading, linearLayout, false);
        relativeLayout = (RelativeLayout) viewLoad.findViewById(R.id.LoadingAnim_RL);
        ImageView imageView = (ImageView) viewLoad.findViewById(R.id.LoadingAnim_IV);
        animation = AnimationUtils.loadAnimation(getContext(), R.anim.anim_load);
        LinearInterpolator lin = new LinearInterpolator();
        animation.setInterpolator(lin);
        imageView.startAnimation(animation);
        linearLayout.addView(relativeLayout);
    }

    //移除 "加载中" 动画
    private void removeLoadAnim() {
        animation.cancel();
        linearLayout.removeView(relativeLayout);
    }

    public DisRankItemAdapter getItemAdapter() {
        return itemAdapter;
    }

    @Override
    public void onClick(View v) {
        if (checkNet()) {
            downLoadData();

        } else {
            Toast.makeText(getContext(), "网络连接不可用", Toast.LENGTH_SHORT).show();
        }
    }
}